package com.gingko.duominuo.data.datastore

import androidx.datastore.core.CorruptionException
import androidx.datastore.core.Serializer
import com.gingko.duominuo.proto.SettingPreferences
import com.gingko.duominuo.proto.Settings
import com.google.protobuf.InvalidProtocolBufferException
import java.io.InputStream
import java.io.OutputStream

object SettingsSerializer : Serializer<SettingPreferences> {
    override val defaultValue: SettingPreferences = SettingPreferences.getDefaultInstance()

    override fun readFrom(input: InputStream): SettingPreferences {
        try {
            return SettingPreferences.parseFrom(input)
        } catch (exception: InvalidProtocolBufferException) {
            throw CorruptionException("Cannot read proto.", exception)
        }
    }

    override fun writeTo(
        t: SettingPreferences,
        output: OutputStream
    ) = t.writeTo(output)
}